#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"

int
main(int argc, char* argv[])
{
	if (argc != 2) {
    		printf(2, "Usage: check2 <amount>\n");
    		exit();
  	}
	
	int check;
	int amount = atoi(argv[1]);
	int still_in = 3;

	char* buf = (char*)malloc(amount + 1);

	if(amount < 1){
		printf(2, "a positive amount is required\n");
		exit();
	}

	int fda = open("a.txt",O_RDONLY);
	if(fda < 0) {
		printf(2,"ERROR");
		exit();
	}
	int fdb = open("b.txt",O_RDONLY);
	if(fdb < 0) {
		printf(2,"ERROR");
		exit();
	}
	int fdc = open("c.txt",O_RDONLY);
	if(fdc < 0) {
		printf(2,"ERROR");
		exit();
	}
	
	while (still_in == 3){
		check = read(fda, buf, amount);
		//printf(1, "a check is %d\n", check);
		if(check == 0){
			//printf(1, "read from a.txt. still in reducing to 2\n");
			close(fda);
			still_in = still_in -1;
		}
		check = read(fdb, buf, amount);
		//printf(1, "b check is %d\n", check);
		if(check == 0){
			//printf(1, "read from b.txt. still in reducing to 1\n");
			close(fdb);
			still_in = still_in -1;
		}
		check = read(fdc, buf, amount);
		//printf(1, "c check is %d\n", check);
		if(check == 0){
			//printf(1, "read from c.txt. still in reducing to 0\n");
			close(fdc);
			still_in = still_in -1;
		}	
	}

	
	while (still_in == 2){

		check = read(fdb, buf, amount);
		if(check == 0){
			//printf(1, "read from b.txt. still in reducing to 1\n");
			close(fdb);
			still_in = still_in -1;
		}
		check = read(fdc, buf, amount);
		if(check == 0){
			//printf(1, "read from c.txt. still in reducing to 0\n");
			close(fdc);
			still_in = still_in -1;
		}	

	}

	while (still_in == 1){
		check = read(fdc, buf, amount);
		if(check == 0){
			//printf(1, "read from c.txt. still in reducing to 0\n");
			close(fdc);
			still_in = still_in -1;
		}
	}
	exit();
} 
